<template>
  <el-dialog :modelValue="modelValue" @update:modelValue="(v) => $emit('update:modelValue', v)" title="Shipping address">
    <el-form ref="form" :model="values" :rules="rules">
      <el-form-item label="管理员名称" :label-width="140">
        <el-input v-model="values.adminname" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" :label-width="140">
        <el-input v-model="values.password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="角色" :label-width="140">
        <el-radio-group v-model="values.role">
          <el-radio :label="1">管理员</el-radio>
          <el-radio :label="2">超级管理员</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="权限" :label-width="140">
        <el-tree
          ref="tree"
          :data="menus"
          show-checkbox
          node-key="name"
          :props="{ label: 'title', children: 'items' }"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleDone">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
import { menus } from '@/router/routes'
import { postAdminItemApi } from '@/api/user'
import _ from 'lodash'
const initialValues = {
  adminname: '',
  password: '',
  role: 1,
  checkedKeys: []
}
export default {
  name: 'AdminControl',
  props: ['modelValue'],
  emits: ['update:modelValue'],
  data () {
    return {
      menus,
      values: _.cloneDeep(initialValues),
      rules: {
        adminname: [{ required: true, message: 'adminname必填' }],
        password: [{ required: true, message: 'password必填' }]
      }
    }
  },
  methods: {
    handleDone () {
      // 1. 重置表单
      this.values = _.cloneDeep(initialValues)
      // 控制tree重置
      this.$refs.tree.setCheckedKeys([], false)
      // 2. 触发update:modelValue更改父组件v-model绑定的数据,从而关闭弹框
      this.$emit('update:modelValue', false)
    },
    handleSubmit () {
      // 1.调用接口
      this.$refs.form.validate().then(async (result) => {
        if (result) {
          try {
            await postAdminItemApi({ ...this.values, checkedKeys: this.$refs.tree.getCheckedKeys(false) })
            this.handleDone()
          } catch (error) {}
        }
      })
      // 2. handleDone
    }
  },
  mounted () {
    console.log(menus)
  }
}
</script>